<template>
  <a-space>
    <a-select v-model:value="province" style="width: 120px" :fieldNames="fieldNames" :options="provinces"
      placeholder="选择省市" @change="onProvinceSelect"></a-select>
    <a-select v-model:value="city" style="width: 120px" :fieldNames="fieldNames" :options="cities" placeholder="选择市"
      @change="onCitySelect"></a-select>
    <a-select v-model:value="district" style="width: 120px" :fieldNames="fieldNames" :options="districts"
      placeholder="选择区县" @change="onDistrictSelect"></a-select>
  </a-space>
</template>

<script setup>
import { nextTick, onMounted, ref, watch, toRaw } from 'vue'
import level3 from '@/assets/level3.json'
import { findItemInTree } from '@/mixin'

const props = defineProps({
  value: {
    type: [Array , Object],
    default: () => ['重庆市', '重庆城区', '渝中区']
  }
})
const emit = defineEmits(['update:value'])

const province = ref()
const city = ref()
const district = ref()
// 选项
const provinces = ref(level3)
const cities = ref([])
const districts = ref([])
const fieldNames = {
  label: 'name',
  value: 'name',
}
const emitTrigger = ref(false)

onMounted(() => {
  parseProps()
})

watch(() => props.value, () => {
  parseProps()
})

const parseProps = () => {
  if (props.value && props.value.length == 3) {
    const p = props.value[0]
    const c = props.value[1]
    const d = props.value[2]
    emitTrigger.value = false
    onProvinceSelect(p, findItemInTree(level3, i => i.name == p))
    nextTick(() => {
      onCitySelect(c, findItemInTree(level3, i => i.name == c))
      nextTick(() => {
        onDistrictSelect(d, findItemInTree(level3, i => i.name == d))
      })
    })
  }
}


const onProvinceSelect = (v, n) => {
  const o = n || findItemInTree(level3, i => i.name == v)
  province.value = v;
  cities.value = o.children;
  city.value = o.children[0].name
  districts.value = o.children[0].children
  district.value = o.children[0].children[0].name;

  emitUpdate()
}
const onCitySelect = (v, n) => {
  const o = n || findItemInTree(level3, i => i.name == v)
  city.value = v;
  districts.value = o.children;
  district.value = o.children[0].name

  emitUpdate()
}
const onDistrictSelect = (v, n) => {
  //const o = n || findItemInTree(level3, i => i.name == v)
  district.value = v;
  emitTrigger.value = true;
  emitUpdate()
}

const emitUpdate = () => {
  if (emitTrigger.value) {
    emit('update:value', {
      province: toRaw(findItemInTree(level3, i => i.name == province.value)),
      city: toRaw(findItemInTree(level3, i => i.name == city.value)),
      district: toRaw(findItemInTree(level3, i => i.name == district.value)),
    })
  }
}

</script>

<style lang="less" scoped></style>